from flask import Blueprint, request, jsonify
import pandas as pd
import traceback
from pred import get_result  # 导入 pre.py 中的 get_result 函数
import MySQLdb.cursors
from extensions import mysql  # 从 extensions 导入 mysql 实例
fraud = Blueprint('fraud', __name__)

@fraud.route('/api/predict', methods=['POST'])
def predict():
    """
    接收前端传来的交易信息，调用 pre.py 中的 get_result 进行预处理和预测，并返回结果。
    """
    try:
        if not request.json:
            return jsonify({"error": "请求体非 JSON 格式"}), 400


        data = request.json

        # 检查必须字段是否存在（需包含 pre.py 中需要的所有字段）
        required_fields = [
            "transaction_id", "user_id", "transaction_amount", "transaction_type",
            "transaction_timestamp", "account_balance", "device_type", "location",
            "merchant_category", "ip_address_flag", "previous_fraudulent_activity",
            "daily_transaction_count", "avg_transaction_amount_7d", "failed_transaction_count_7d",
            "card_type", "card_age", "transaction_distance", "authentication_method",
            "risk_score", "is_weekend", "fraud_label"
        ]

        missing_fields = [f for f in required_fields if data.get(f) is None]
        if missing_fields:
            return jsonify({"error": f"缺少必要字段: {missing_fields}"}), 400

        transaction_id=data.get('transaction_id')

        # 构造 DataFrame，字段名保持小写
        new_data = pd.DataFrame([{
            "transaction_id": data.get("transaction_id"),
            "user_id": data.get("user_id"),
            "transaction_amount": data.get("transaction_amount"),
            "transaction_type": data.get("transaction_type"),
            "transaction_timestamp": data.get("transaction_timestamp"),
            "account_balance": data.get("account_balance"),
            "device_type": data.get("device_type"),
            "location": data.get("location"),
            "merchant_category": data.get("merchant_category"),
            "ip_address_flag": data.get("ip_address_flag"),
            "previous_fraudulent_activity": data.get("previous_fraudulent_activity"),
            "daily_transaction_count": data.get("daily_transaction_count"),
            "avg_transaction_amount_7d": data.get("avg_transaction_amount_7d"),
            "failed_transaction_count_7d": data.get("failed_transaction_count_7d"),
            "card_type": data.get("card_type"),
            "card_age": data.get("card_age"),
            "transaction_distance": data.get("transaction_distance"),
            "authentication_method": data.get("authentication_method"),
            "risk_score": data.get("risk_score"),
            "is_weekend": data.get("is_weekend"),
            "fraud_label": data.get("fraud_label")
        }])

        print(new_data)

        # 调用 pre.py 中的 get_result 函数
        prediction, prob = get_result(new_data)

        # 处理预测结果
        result = int(prediction[0])  # 假设 prediction 返回的是一个数组
        probability = float(prob[0])

        # 更新数据库
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)

        cursor.execute('UPDATE transactions SET fraud_label = %s WHERE transaction_id = %s',
                       (result, transaction_id))

        mysql.connection.commit()

        return jsonify({
            "user_id": data.get("user_id"),
            "prediction": result,
            "probability": probability,
            "message": f"交易预测结果：{'欺诈' if result == 1 else '正常'}"
        }), 200

    except Exception as e:
        traceback.print_exc()
        return jsonify({"error": str(e)}), 500
